

#import "UIView+Loading.h"
#import <objc/message.h>

@interface NSMMaskView : UIView {
    UIActivityIndicatorView *_indicatorView;
}
- (void)startAnimating;
- (void)stopAnimating;
@end

@implementation NSMMaskView
- (instancetype)init {
    self = [super init];
    if (self) {
        _indicatorView = [UIActivityIndicatorView new];
        _indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
        [self addSubview:_indicatorView];
    }
    return self;
}

- (void)startAnimating {
    [_indicatorView startAnimating];
}

- (void)stopAnimating {
    [_indicatorView stopAnimating];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    UIView *parent = self.superview;
    if (parent) self.frame = parent.bounds;
    
    _indicatorView.center = CGPointMake(self.bounds.size.width / 2,
                                        self.bounds.size.height / 2);
}
@end

@interface UIView (UIActivityIndicatorView)
@property (nonatomic, strong) NSMMaskView *maskView;
@end

@implementation UIView (UIActivityIndicatorView)
- (NSMMaskView *)maskView {
    NSMMaskView *view = objc_getAssociatedObject(self, _cmd);
    if (!view) {
        view = [NSMMaskView new];
        [self setMaskView:view];
    }
    return view;
}

- (void)setMaskView:(NSMMaskView *)maskView {
    objc_setAssociatedObject(self, @selector(maskView), maskView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end


@implementation UIView (Loading)

- (BOOL)isLoading {
    NSNumber *obj = objc_getAssociatedObject(self, _cmd);
    return obj.boolValue;
}

- (void)setIsLoading:(BOOL)isLoading {
    objc_setAssociatedObject(self, @selector(isLoading), @(isLoading), OBJC_ASSOCIATION_ASSIGN);
    
    if (isLoading) {
        if (self.maskView.superview) [self.maskView removeFromSuperview];
        
        [self.maskView startAnimating];
        [self addSubview:self.maskView];
    } else {
        [self.maskView stopAnimating];
        
        if (self.maskView.superview) [self.maskView removeFromSuperview];
    }
}

@end
